package org.example.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.order.common.GoodFilter;
import org.example.order.entity.Classification;
import org.example.order.entity.Good;
import org.example.order.exception.GoodNotFoundException;
import org.example.order.exception.IllegalGoodFilterException;
import org.example.order.mapper.GoodMapper;
import org.example.order.service.GoodService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class GoodServiceImpl implements GoodService {
    @Resource
    private GoodMapper mapper;

    @Override
    public PageInfo<Good> getGoodsByFilter(GoodFilter goodFilter) throws IllegalGoodFilterException {
        goodFilter.checkFilter();
        BigDecimal priceStart = goodFilter.getPriceStart() == null ? null : BigDecimal.valueOf(goodFilter.getPriceStart());
        BigDecimal priceEnd = goodFilter.getPriceEnd() == null ? null : BigDecimal.valueOf(goodFilter.getPriceEnd());
        PageHelper.startPage(goodFilter.getPageNum(), goodFilter.getPageSize());
        List<Good> goods = mapper.selectByFilter(
                goodFilter.getName(),
                goodFilter.getClassification(),
                goodFilter.getStatus(),
                priceStart,
                priceEnd
        );
        return new PageInfo<>(goods);
    }

    @Override
    public Good getGood(Long id) {
        return mapper.selectById(id);
    }

    @Override
    public void addGood(Good good) {
        if (good.getClassification() == null) {
            good.setClassification(new Classification());
        }
        int count = mapper.insertGood(good);
        if (count == 0) {
            throw new RuntimeException("插入商品表失败");
        }
    }

    @Override
    public void deleteGood(Long id) {
        int count = mapper.deleteGood(id);
        if (count == 0) {
            throw new GoodNotFoundException("商品不存在，删除失败");
        }
    }

    @Override
    public void updateGood(Good good) {
        int count = mapper.updateGood(good);
        if (count == 0) {
            throw new GoodNotFoundException("商品不存在，更新失败");
        }
    }
}
